﻿using BCCommon;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using BCEntity.Sim.Admin.TreePermission;
using System.Data;

namespace BCData.Sim.Admin.TreePermission
{
    public class TreePermissionRecordData : ITreePermissionRecordData
    {
        private readonly IDatabaseContext database;

        private const string QUERY = @"SELECT TreePermissionRecordId,TreePermissionConfigId,CompanyId,DepartmentId,AdminId,StaffOrganizationMappingRecordId,CreateTime,CreateAdminId,CreateAdminName,
                                    EditAdminId,EditAdminName,UpdateTime FROM TreePermissionRecord";

        private const string QUERY_JOIN = @"SELECT A.TreePermissionRecordId,A.CompanyId,A.DepartmentId,A.AdminId,A.StaffOrganizationMappingRecordId,
                                        B.TreePermissionConfigId,B.PermissionName,B.PermissionType,B.PermissionCode,B.PermissionPathCode,B.ParentPermissionPathCode,
                                        B.PermissionLevel,B.PermissionOrder,B.PagePathCode,B.Icon,B.IsShow,B.CreateTime
                                        FROM TreePermissionRecord A 
                                        INNER JOIN TreePermissionConfig B ON A.TreePermissionConfigId = B.TreePermissionConfigId";

        public TreePermissionRecordData(IDatabaseContext database)
        {
            this.database = database;
        }

        public async Task<int> Delete(long treePermissionConfigId)
        {
            return await database.Master.ExecuteAsync("DELETE FROM TreePermissionRecord WHERE TreePermissionConfigId = ?TreePermissionConfigId", new { treePermissionConfigId }, database.Transaction);
        }

        public async Task<TreePermissionRecordEntity> GetEntityByAdminIdAsync(long adminId, long treePermissionConfigId)
        {
            return await database.Slave.QueryFirstOrDefaultAsync<TreePermissionRecordEntity>($"{QUERY} WHERE AdminId = ?AdminId AND TreePermissionConfigId = ?TreePermissionConfigId", new { adminId, treePermissionConfigId });
        }

        public async Task<TreePermissionRecordEntity> InsertAsync(TreePermissionRecordEntity entity)
        {
            return await database.Master.InsertAsync(entity);
        }

        public async Task<int> DeleteStaffOrganizationMappingRecordId(long treePermissionConfigId, long staffOrganizationMappingRecordId)
        {
            return await database.Master.ExecuteAsync("DELETE FROM TreePermissionRecord WHERE TreePermissionConfigId = ?TreePermissionConfigId AND StaffOrganizationMappingRecordId = ?StaffOrganizationMappingRecordId", new { treePermissionConfigId, staffOrganizationMappingRecordId });
        }

        public async Task<TreePermissionRecordEntity> GetEntityByDepartmentIdAsync(int departmentId, long treePermissionConfigId)
        {
            return await database.Slave.QueryFirstOrDefaultAsync<TreePermissionRecordEntity>($"{QUERY} WHERE DepartmentId = ?DepartmentId AND AdminId IS NULL AND TreePermissionConfigId = ?TreePermissionConfigId", new { departmentId, treePermissionConfigId });
        }

        public async Task<TreePermissionRecordEntity> GetEntityByCompanyIdAsync(int companyId, long treePermissionConfigId)
        {
            return await database.Slave.QueryFirstOrDefaultAsync<TreePermissionRecordEntity>($"{QUERY} WHERE CompanyId = ?CompanyId AND AdminId IS NULL AND TreePermissionConfigId = ?TreePermissionConfigId", new { companyId, treePermissionConfigId });
        }

        public async Task<int> DeleteDepartment(long treePermissionConfigId, int departmentId)
        {
            return await database.Master.ExecuteAsync("DELETE FROM TreePermissionRecord WHERE TreePermissionConfigId = ?TreePermissionConfigId AND DepartmentId = ?DepartmentId", new { treePermissionConfigId, departmentId });
        }

        public async Task<int> DeleteCompany(long treePermissionConfigId, int companyId)
        {
            return await database.Master.ExecuteAsync("DELETE FROM TreePermissionRecord WHERE TreePermissionConfigId = ?TreePermissionConfigId AND CompanyId = ?CompanyId", new { treePermissionConfigId, companyId });
        }

        public async Task<IEnumerable<TreePermissionRecordViewEntity>> GetList(int? companyId, int? departmentId, long? staffOrganizationMappingRecordId)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();
            if (companyId.HasValue)
            {
                wheres.Add("A.CompanyId = ?CompanyId AND A.DepartmentId IS NULL");
                parameters.Add("?CompanyId", companyId.Value, DbType.Int32);
            }
            if (departmentId.HasValue)
            {
                wheres.Add("A.DepartmentId = ?DepartmentId AND A.AdminId IS NULL");
                parameters.Add("?DepartmentId", departmentId.Value, DbType.Int32);
            }
            if (staffOrganizationMappingRecordId.HasValue)
            {
                wheres.Add("A.StaffOrganizationMappingRecordId = ?StaffOrganizationMappingRecordId");
                parameters.Add("?StaffOrganizationMappingRecordId", staffOrganizationMappingRecordId.Value, DbType.Int64);
            }
            string sql = string.Format("{0} {1}", QUERY_JOIN, wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : string.Empty);
            return await database.Slave.QueryAsync<TreePermissionRecordViewEntity>(sql, parameters);
        }

        public async Task<IEnumerable<TreePermissionConfigEntity>> GetListByAdminIdAsync(long? staffOrganizationMappingRecordId)
        {
            DynamicParameters parameters = new DynamicParameters();
            string sql = @"SELECT TreePermissionConfigId,PermissionName,PermissionType,PermissionCode,PermissionPathCode,ParentPermissionPathCode,
                        PermissionLevel,PermissionOrder,PagePathCode,Icon,IsShow,CreateTime 
                        FROM TreePermissionConfig
                        ORDER BY PermissionPathCode, PermissionLevel;";
            if (staffOrganizationMappingRecordId.HasValue)
            {
                sql = @"SELECT A.TreePermissionConfigId,A.PermissionName,A.PermissionType,A.PermissionCode,A.PermissionPathCode,A.ParentPermissionPathCode,
                            A.PermissionLevel, A.PermissionOrder, A.PagePathCode, A.Icon, A.IsShow
                        FROM TreePermissionConfig A
                        INNER JOIN TreePermissionRecord B ON A.TreePermissionConfigId = B.TreePermissionConfigId
                        WHERE B.StaffOrganizationMappingRecordId=?StaffOrganizationMappingRecordId;";
                parameters.Add("?StaffOrganizationMappingRecordId", staffOrganizationMappingRecordId.Value, DbType.Int64);
            }
            return await database.Slave.QueryAsync<TreePermissionConfigEntity>(sql, parameters);
        }

        public async Task<IEnumerable<TreePermissionRecordViewEntity>> GetPermissionRecordListByAdminId(long? adminId)
        {
            DynamicParameters parameters = new DynamicParameters();
            string sql = @"SELECT TreePermissionConfigId,PermissionName,PermissionType,PermissionCode,PermissionPathCode,ParentPermissionPathCode,
                        PermissionLevel,PermissionOrder,PagePathCode,Icon,IsShow,CreateTime 
                        FROM TreePermissionConfig
                        ORDER BY PermissionPathCode, PermissionLevel;";
            if (adminId.HasValue)
            {
                sql = @"SELECT A.TreePermissionConfigId,A.PermissionName,A.PermissionType,A.PermissionCode,A.PermissionPathCode,A.ParentPermissionPathCode,
                            A.PermissionLevel, A.PermissionOrder, A.PagePathCode, A.Icon, A.IsShow
                        FROM TreePermissionConfig A
                        INNER JOIN TreePermissionRecord B ON A.TreePermissionConfigId = B.TreePermissionConfigId
                        WHERE B.AdminId = ?AdminId;";
                parameters.Add("?AdminId", adminId.Value, DbType.Int64);
            }
            return await database.Slave.QueryAsync<TreePermissionRecordViewEntity>(sql, parameters);
        }
    }
}
